package com.buaa.airticketbookingsystem.Controller;

import com.buaa.airticketbookingsystem.Entity.PurchaseRecord;
import com.buaa.airticketbookingsystem.Entity.Ticket;
import com.buaa.airticketbookingsystem.Entity.User;
import com.buaa.airticketbookingsystem.Service.PurchaseRecordService;
import com.buaa.airticketbookingsystem.Service.TicketService;
import com.buaa.airticketbookingsystem.Service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
@CrossOrigin
@RestController
public class RefundController {
    @Autowired
    private PurchaseRecordService purchaseRecordService;

    @Autowired
    private UserService userService;

    @Autowired
    private TicketService ticketService;

    @PostMapping("/refund")
    public Map<String, Object> refund(@RequestBody Map<String, String> remap){
        Map<String, Object> map = new HashMap<>();
        String no = remap.get("no");
        try {
            long time = new Date().getTime();
            PurchaseRecord pr = purchaseRecordService.getPurchaseRecordByNo(no);
            ticketService.add(pr.getT_id());
            userService.charge(pr.getEmail(), pr.getPrice());
            purchaseRecordService.refund(no);
            User u = userService.selectUserByEmail(pr.getEmail());
            if((u.getLast_refund() + (30 * 24 * 60 * 60)) < time/1000 || u.getLast_refund() == 0){
                System.out.println("===========");
                System.out.println(u.getLast_refund() + 30 * 24 * 60 * 60 < time);
                System.out.println(u.getLast_refund() == 0 );
                System.out.println(u.getLast_refund());
                System.out.println(time);
                userService.refund(time, pr.getEmail());
                userService.highCredit(pr.getEmail());
            }
            else if((u.getLast_refund() + 30 * 24 * 60 * 60) >= time /1000){
                System.out.println("-----");
                userService.refund(time, pr.getEmail());
                userService.lowCredit(pr.getEmail());
            }
            map.put("res", true);
            map.put("message", "退款成功！");
            return map;
        }
        catch (Exception e) {
            e.printStackTrace();
            map.put("res", false);
            map.put("message", "退款失败！");
            return map;
        }
    }

}
